package com.recharge.sup.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.recharge.OrderService;
import com.recharge.domain.TradeFlow;
import com.recharge.domain.TradeOrder;
import com.recharge.mapper.ITradeOrderMapper;
import com.recharge.sup.AbsSupChargeService;
import com.recharge.utils.HttpClientUtils;
import com.recharge.utils.ProcessResult;

@Service
public class YunllTaiWeiHfChargeServiceImpl extends AbsSupChargeService{
	@Value("${yunllhf.sendUrl}")
    private String sendUrl ;
	
	@Value("${yunllhf.balance}")
    private String balance ;
	
    @Value("${yunllhf.callBackUrl}")
    private String callBackUrl ;
	
	@Value("${yunllhf.merchant_id}")
    private String merchant_id ;
	
	@Value("${yunllhf.key}")
    private String key ;
	
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private ITradeOrderMapper iTradeOrderMapper;

    private Logger logger = LoggerFactory.getLogger(getClass());

    //充值发送订单
	@Override
	public ProcessResult recharge(TradeOrder tradeOrder, TradeFlow tradeFlow) {
		String merchant_orderid = tradeOrder.getOrderId();//商户订单号
		String charge_number = tradeOrder.getChargeNumber();//充值手机号
		Long charge_money = tradeOrder.getChargeMoney();//充值金额
		String busi_type = tradeOrder.getBusiType() + "";  //充值类型
		String back_url = balance;
		busi_type = "0";  //0为手机充值类型
		String sendStr= "order" + merchant_id + merchant_orderid +
				 charge_number + charge_money + busi_type + back_url + key;
		String sign = DigestUtils.md5Hex("order" + merchant_id + merchant_orderid +
				 charge_number + charge_money + busi_type + callBackUrl + key);
		String sendData = "service=order&merchant_id="+merchant_id+"&merchant_orderid="+
				 merchant_orderid+"&charge_number="+charge_number+"&charge_money="+
				 charge_money+"&busi_type="+busi_type+"&back_url="+callBackUrl+"&sign="+sign;
		logger.info("orderId:{}发送云流量话费数据,sendData:{}", merchant_orderid , sendData);
		String result = null;
		try {
			result = HttpClientUtils.invokeGetHttp(sendUrl + "?" + sendData, "utf-8", 3000);
			logger.info("orderId:{}发送云流量话费返回,result:{}", merchant_orderid , result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String result_desc = null;
        if (result != null && !"".equals(result)) {
            Map<String, String> rspMap = getMapParamter(result);
            String orderId = "";
            String code = rspMap.get("result_code");
            result_desc = rspMap.get("result_desc");

            iTradeOrderMapper.updateProcessStatus(merchant_orderid,result_desc);
            if ("0000".equals(code)) {
                orderId = rspMap.get("orderid");
                logger.info("orderid : {}发送云流量话费成功 . yll orderId:{}",tradeOrder.getOrderId(),orderId);
                ProcessResult processResult = new ProcessResult();
                processResult.setCode(ProcessResult.SUCCESS);
                return processResult;
            }else{
                orderId = rspMap.get("orderid");
                logger.info("orderid : {}发送云流量话费失败. yll orderId:{}",tradeOrder.getOrderId(),orderId);
                ProcessResult processResult = new ProcessResult();
                processResult.setCode(ProcessResult.FAIL);
                return processResult;
            }
        }
        logger.info("orderId:{}发送结果可疑", merchant_orderid);
        ProcessResult processResult = new ProcessResult();
        processResult.setCode(ProcessResult.UNKNOWN);
        return processResult;
	}

	@Override
	public void response(TradeOrder tradeOrder, TradeFlow tradeFlow, Map<String, String> responseMap) {
		String order_id = responseMap.get("order_id");          //订单号
		String charge_status = responseMap.get("charge_status");//状态
		logger.info("orderId:{}回调云流量话费状态charge_status：{}", order_id,charge_status);
    	//修改订单处理状态为3（回调过）
        if (StringUtils.equals("SUCC",charge_status)){
            orderService.SUCCESS(tradeOrder,tradeFlow);
        }else if (StringUtils.equals("FAIL",charge_status)){
            orderService.FAIL(tradeOrder, tradeFlow);
        }else{
            orderService.UNKNOWN(tradeOrder, tradeFlow);
        }
	}

	@Override
	public ProcessResult query(TradeOrder tradeOrder, TradeFlow tradeFlow) {
		String merchant_orderid = tradeOrder.getOrderId(); //商户订单号
		String sign = DigestUtils.md5Hex("query" + merchant_id + merchant_orderid + key);
		String sendData = "service=query&merchant_id=" + merchant_id + "&merchant_orderid=" +
				merchant_orderid + "&sign=" +sign;
		logger.info("orderid：{},查询云流量话费数据sendData:{}",merchant_orderid,sendData);
		String result = null;
		try {
			result = HttpClientUtils.invokeGetHttp(sendUrl + "?" + sendData, "utf-8", 3000);
			logger.info("orderid：{},查询到云流量话费返回result:{}",merchant_orderid,result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String result_desc = null;
		String chargestatus = null;
		if (result != null && !"".equals(result)) {
            Map<String, String> rspMap = getMapParamter(result);
            String code = rspMap.get("result_code");//返回编码
            result_desc = rspMap.get("result_desc");//返回结果描述
            chargestatus = rspMap.get("chargestatus");//返回订单状态
            iTradeOrderMapper.updateProcessStatus(merchant_orderid,result_desc);
            logger.info("orderid : {}查询到云流量话费 result_desc:{}",merchant_orderid,result_desc);
            ProcessResult processResult = new ProcessResult();
            if ("SUCC".equals(chargestatus)) {
            	processResult.setCode(ProcessResult.SUCCESS);
            	iTradeOrderMapper.updateProcessStatus(merchant_orderid,result_desc);
            }else if("DEAL".equals(chargestatus)){
            	processResult.setCode(ProcessResult.PROCESSING);
            	iTradeOrderMapper.updateProcessStatus(merchant_orderid,result_desc);
            }else if("FAIL".equals(chargestatus)){
            	processResult.setCode(ProcessResult.FAIL);
            	iTradeOrderMapper.updateProcessStatus(merchant_orderid,result_desc);
            }else{
                processResult.setCode(ProcessResult.UNKNOWN);
            }
            return processResult;
        }
        logger.info("orderId:{}发送查询可疑", merchant_orderid);
        ProcessResult processResult = new ProcessResult();
        processResult.setCode(ProcessResult.UNKNOWN);
        return processResult;
	}

	public static Map<String,String> getMapParamter(String paramter){
        Map<String,String> map = new HashMap<String,String>();
        String[] splitparam = paramter.split("\\&");
        for(int i=0; i<splitparam.length; i++){
            String[] splitpm = splitparam[i].split("=");
            if(splitpm.length<2){
                map.put(splitpm[0], "");
            }else{
                map.put(splitpm[0], splitpm[1]);
            }
        }
        return map;
    }
	
	public static void main(String[] args) {
		String service = "balance";
		String merchant_id = "test";
		String sign = DigestUtils.md5Hex(service+merchant_id+"1234567890");
		String sendData = "service=balance&merchant_id="+merchant_id+ "&sign=" + sign;
		String result = null;
		try {
			result = HttpClientUtils.invokeGetHttp("http://101.201.61.186:18200/request.do"+ "?" + sendData,"utf-8", 3000);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(result);
		Map<String, String> rspMap = getMapParamter(result);
		String result_code = rspMap.get("result_code");
		String result_desc = rspMap.get("result_desc");
		String balance = rspMap.get("balance");
		System.out.println(result_code+"+"+result_desc+"+"+balance);
		
	}
}
